import storyWithproject from '@/models/storyWithproject';
import { ObjectId } from 'mongodb';
import { getSingleBranch } from '../gitlab/apis';
import { syncPostNewBranch, syncProjectsSearch } from '../gitlab/index';
import { privateToken } from '../configs/gitlab';
import { gitlabOApiFetch } from '../fetch';

const gitlabApi = gitlabOApiFetch();

// 给需求添加项目
export const addRelative = async (params) => {
  const result = await storyWithproject.insert({ ...params, pid: null });
  return result;
};
// 获取需求下关联的项目
export const getRelative = async (params) => {
  const result = await storyWithproject.getStoryWithProject(params);
  return result;
};
// 删除需求关联的项目
export const deleteRelative = async (params) => {
  const { id, project_id, branch, parentid, env } = params;
  console.log(id, project_id, branch, parentid, env);
  await storyWithproject.deleteOne({ id, project_id, branch });
  // 看看这个分支有没有合并分支，如果有。看看这个这个合并分支下还有其他分支，如果没有，合并分支也一起删除，如果剩一个，那个删除合并分支，改变剩余分支的父节点。
  if (parentid) {
    const brotherBranch = await storyWithproject.getList({ parentid, project_id });
    if (brotherBranch.length === 1) {
      const item = brotherBranch[0];
      // 删除合并分支
      await storyWithproject.deleteOne({ id, project_id, env, type: 2 });
      // 把剩下的这个分支的父节点重置到环境上
      await storyWithproject.update({ parentid: `${project_id as string}$${env as string}` }, { id: item.id, branch: item.branch, project_id: item.project_id });
    }
  }
  return [];
};
// 编辑需求关联的某个项目
export const updateRelative = async (params) => {
  const { id, project_name, branch, review_status, env } = params;
  const result = await storyWithproject.update({ review_status, env }, { id, project_name, branch });
  return result;
};

// 获取所有需求列表和管理的项目
export const getListAll = async (params) => {
  // 获取所有需求关联的项目，已经上线的需求除外
  const result = await storyWithproject.getListAll();
  // 获取所有需求。过滤掉已上线的
  return result;
};

// 在脑图上创建合并分支
export const asyncCreateMergeBranch = async (params) => {
  // info： 项目id$环境$分支名称$需求id
  const { projectId, mergeBranchName, node } = params;
  const info = node[0];
  // 判断gitlab上有没有这个分支
  const branchRes: any = await getSingleBranch({ private_token: privateToken, id: Number(projectId), branch: mergeBranchName }).catch((err) => {
    return null;
  });
  // 如果不存在
  if (!branchRes || !branchRes.name) {
    const project = await syncProjectsSearch({ id: Number(projectId) });
    let default_branch = 'master';
    if (project.length) {
      default_branch = project[0].default_branch;
    }
    // 往gitlab上发个创建合并分支的请求。基于主分支创建一个新的分支
    await syncPostNewBranch({ id: projectId, ref: default_branch, branch: mergeBranchName });
  }
  // 往需求关联项目的表里新增这个分支
  const infoArr: string[] = info.split('$');
  const temp = {
    project_id: Number(infoArr[0]),
    env: infoArr[1],
    id: infoArr[3],
    parentid: `${infoArr[0]}$${infoArr[1]}`,
    branch: mergeBranchName,
    type: 2,
  };
  // 插入新数据
  await storyWithproject.insert(temp);

  // 更新旧数据
  let index = 0;
  const loop = async () => {
    if (index >= node.length) return [];
    const arr = node[index].split('$');
    await storyWithproject.update(
      { parentid: `${infoArr[0]}$${infoArr[1]}$${mergeBranchName as string}$${infoArr[3]}` },
      {
        branch: arr[2],
        project_id: Number(arr[0]),
      },
    );
    index += 1;
    loop();
    return [];
  };
  loop();
  return [];
};

// 手动更新代码合并状态
export const manualUpdateMergeStatus = async (params) => {
  const { id, source_branch, _id } = params;
  const res = await storyWithproject.update({ isMergeToMain: 1, mr: '' }, { _id: new ObjectId(_id) });
  return res;
};
